package com.wn.class30.cotroller.houtai;

import com.wn.class30.entity.AdminUser;
import com.wn.class30.entity.Systemmenu;
import com.wn.class30.service.AdminUserService;
import com.wn.class30.service.SystemmenuService;
import com.wn.class30.tools.Md5Utils;
import com.wn.class30.tools.MenuTree;
import com.wn.class30.tools.Result;
import com.wn.class30.tools.SMSUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: AdminUserController 后台管理员和商家登陆类
 * @author: jzy
 * @date: 2020/3/30 8:03 PM
 */
@RestController
@Slf4j
@RequestMapping("/houtai/adminuser")
public class AdminUserController {
    @Resource
    private AdminUserService adminUserService;
    private Map<String,String> map = new HashMap<>();
    @Resource
    private SystemmenuService systemmenuService;
    /**
     * 登陆方法
     * @param tel 电话
     * @param adminUserPwd 密码
     * @param rememberMe 是否勾选记住密码
     * @return
     * @throws Exception
     */
    @RequestMapping("/login")
    public Result login(String tel,String adminUserPwd,boolean rememberMe)throws Exception{
        //把客户端用户输入的用户名、密码、记住我信息封装到token里面
        UsernamePasswordToken token = new UsernamePasswordToken(tel, Md5Utils.getMD5(adminUserPwd),rememberMe);
        //获取subject对象，该对象代表一个具体的客户端
        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject.isAuthenticated());
        Result result = new Result();
        result.setCode("200");
        result.setMassage("success");

        //判断该客户端是否已经登陆或者使用了记住我功能
        if(!subject.isAuthenticated() && !subject.isRemembered()){
            //如果没有登陆并且没有使用rememberMe，则进行登录验证,并把token传入进去，realm会校验用户名和密码
            subject.login(token);
            return result;
        }
        return result;
    }
    @RequestMapping("/user/selectMenuTree")
    public Result selectMenuTreeByUid(HttpSession session)throws Exception{
        System.out.println("查询权限了。。。。。。。。");
        Subject subject = SecurityUtils.getSubject();
        AdminUser userInfo = (AdminUser) subject.getPrincipal();
        Set<Systemmenu> set = systemmenuService.queryPressionByUserInfo(userInfo.getAdminUserId());
        List<Systemmenu> menuTree = MenuTree.getMenuTree(set);
        for (Systemmenu systemmenu : menuTree) {
            if(systemmenu.getMenuId()==1){
                menuTree.remove(systemmenu);
                break;
            }
        }

        session.setAttribute("menuTree",menuTree);
        return new Result("200", userInfo.getAdminUserName(), null, menuTree);
    }
    @RequestMapping("/buttons")
    public Result selectButtons(String url) throws Exception{
        Subject subject = SecurityUtils.getSubject();
        AdminUser userInfo = (AdminUser) subject.getPrincipal();
        Set<Systemmenu> set = systemmenuService.queryPressionByUserInfo(userInfo.getAdminUserId());
        ArrayList<Systemmenu> list = (ArrayList<Systemmenu>) MenuTree.getMenuTree(set);
        System.out.println("url:======="+url);
        ArrayList<Systemmenu> buttons = new ArrayList<>();
        for (Systemmenu menu : list) {
            for (Systemmenu level2 : menu.getChildrens()) {
                if(url.equals(level2.getMenuUrl())) {
                    buttons = (ArrayList<Systemmenu>) level2.getChildrens();
                    break;
                }
            }
        }
        System.out.println("-------------"+buttons.size());
        return new Result("200","success",null,buttons);
    }

    /**
     * 获取验证码
     * @throws Exception
     */
    @RequestMapping("/sendVercode")
    public void sendVercode(String tel)throws Exception{
        log.info("进入发送验证码方法了");
        log.info("前端输入电话:"+tel);
        //判断手机号是否在后台用户表内
        List<AdminUser> adminUsers = adminUserService.selectAdminUsers();
        if(tel != null && tel.trim() != ""){
            for (AdminUser adminUser : adminUsers) {
                if(tel.equals(adminUser.getTel())){
                    //获取随机验证码
                    String vercode = SMSUtils.getVercode();
                    map.put(tel,vercode);
                    //发送验证码
                    SMSUtils.sendShortMessage(tel,vercode );
                    log.info("给"+tel+"发送验证码了"+vercode);
                    break;
                }
            }
        }
    }

    /**
     * 校验短信验证码是否正确
     * @param tel 手机号
     * @param vercode 验证码
     * @return
     * @throws Exception
     */
    @RequestMapping("/checkVercode")
    public Result checkVercode(String tel,String vercode)throws Exception{
        log.info("前端输入电话："+tel);
        log.info("前端输入验证码："+vercode);
        if(tel != null && tel.trim() != "" && vercode != null && vercode.trim() != "" ){
            String code = map.get(tel);
            log.info("map里面的验证码："+code);
            if(code != null && vercode.equals(code)){
                map.remove(tel);
                Result result = new Result();
                result.setCode("200");
                result.setMassage("success");
                return result;
            }else{
                Result result = new Result();
                result.setCode("500");
                result.setMassage("fiald");
                return result;
            }
        }else{
            Result result = new Result();
            result.setCode("500");
            result.setMassage("fiald");
            return result;
        }
    }

    /**
     * 忘记密码修改密码
     * @param tel 电话
     * @param pwd 新密码
     * @return
     * @throws Exception
     */
    @RequestMapping("/updatepwd")
    public Result updatePwd(String tel,String pwd)throws Exception{
        if(pwd != null && pwd.trim() != ""){
            AdminUser adminUser = adminUserService.selectAdminUserByTel(tel);
            adminUser.setAdminUserPwd(Md5Utils.getMD5(pwd));
            adminUserService.updateAdminUser(adminUser);
            Result result = new Result();
            result.setCode("200");
            result.setMassage("success");
            return result;
        }else{
            Result result = new Result();
            result.setCode("500");
            result.setMassage("fiald");
            return result;
        }
    }


}